﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Fis.Service.Forms
{
    public partial class UserEditForm : SaveEditForm
    {
        public UserEditForm()
        {
            InitializeComponent();
        }

        public override void InitializeBinding()
        {
            var d = ViewModel["data"] as DataTable;

            if (ViewState == Agile.Engine.View.ViewState.AddNew)
            {
                d.Rows[0]["FRIGHTS"] = 0;
                d.Rows[0]["FSTATUS"] = 0;
            }

            Fis.Win.Utils.UIUtils.ClearBindings(dataLayoutControl1);
            Fis.Win.Utils.UIUtils.TagBindings(dataLayoutControl1, d);

            Fis.Win.Utils.UIUtils.LookUpBinding(FRIGHTSLookUpEdit, Fis.Win.Utils.AppSession.RightsCache(), "display", "value");
            Fis.Win.Utils.UIUtils.LookUpBinding(FSTATUSLookUpEdit, Fis.Win.Utils.AppSession.StateCache(), "display", "value");
            FUSERNAMETextEdit.Focus();
        }

        protected override void SaveAndClose()
        {
            Validate();

            if (!dxValidationProvider1.Validate())
            {
                return;
            }

            (ViewModel["data"] as DataTable).Rows[0]["FPASSWORD"] = Agile.Engine.Utils.StringUtils.ToMD5(this.FPASSWORDTextEdit.EditValue.ToString());

            if (ViewProvider.ExecuteUpdate(ViewModel))
            {
                ViewResult = System.Windows.Forms.DialogResult.OK;
                Close();
            }
        }

        protected override void SaveAndNew()
        {
            Validate();

            if (!dxValidationProvider1.Validate())
            {
                return;
            }

            (ViewModel["data"] as DataTable).Rows[0]["FPASSWORD"] = Agile.Engine.Utils.StringUtils.ToMD5(this.FPASSWORDTextEdit.EditValue.ToString());

            if (ViewProvider.ExecuteUpdate(ViewModel))
            {
                foreach (var ctl in this.layoutControl1.Controls)
                {
                    var edit = ctl as DevExpress.XtraEditors.BaseEdit;
                    if (edit != null)
                        edit.EditValue = null;
                }

                ViewState = Agile.Engine.View.ViewState.AddNew;
                ViewModel = ViewProvider.InitializeViewModel(new System.Collections.Hashtable());
                InitializeViewUI();
                InitializeBinding();
            }
        }

        private void UserEditForm_Load(object sender, EventArgs e)
        {
            FSTATUSLookUpEdit.Properties.ReadOnly = false;
            barButtonItem3.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
        }
    }
}
